import leancloud
from app.verify.config.sms_config import App_ID,App_Key
import six


def request_sms_code(phone_number, idd='+86', sms_type='sms',
                     validate_token=None, template=None, sign=None,
                     params=None):
    """
    请求发送手机验证码
    :param phone_number: 需要验证的手机号码
    :param idd: 号码的所在地国家代码，默认为中国（+86）
    :param sms_type: 验证码发送方式，'voice' 为语音，'sms' 为短信
    :param template: 模版名称
    :param sign: 短信签名名称
    :return: None
    """
    if not isinstance(phone_number, six.string_types):
        raise TypeError('phone_number must be a string')

    data = {
        'mobilePhoneNumber': idd + phone_number,
        'smsType': sms_type,
    }

    if template is not None:
        data['template'] = template

    if sign is not None:
        data['sign'] = sign

    if validate_token is not None:
        data['validate_token'] = validate_token

    if params is not None:
        data.update(params)

    r = leancloud.client.post('/requestSmsCode', params=data)
    return r

class SMSService(object):
    def __init__(self, op):
        self.App_Key = App_Key
        self.App_ID = App_ID
        self.leancloud = leancloud.init(App_ID, App_Key)
        self.options = {
            "op": op,
            "ttl": 10  # 验证码有效时间为 10 分钟
        }

    def sendSMS(self, telephone):
        r = request_sms_code(telephone, sign="EasyManager", params=self.options)
        if r.status == 200:
            return True

    def verify(self, telephone, code):
        try:
            r = leancloud.cloud.verify_sms_code(telephone, code)
        except:
            return False
        else:
            return True

